package com.tianruan.psychological.common.exception;

import com.tianruan.psychological.common.constant.GlobalExceptionEnum;
import com.tianruan.psychological.common.response.VResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.exceptions.BadClientCredentialsException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liuxin
 * @date 2019/11/9
 * @PS 全局异常接收类
 */
@RestController
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(Exception.class)
    public VResponse<Object> Exception(HttpServletRequest request, Exception exception) {
        return VResponse.error(1000, exception.getMessage());
    }

    @ExceptionHandler(org.springframework.security.access.AccessDeniedException.class)
    public String accessDeniedException(HttpServletRequest request, Exception e) {

        return "现在捕获的是全局异常";
    }

    @ExceptionHandler(RuntimeException.class)
    public String runtimeException(HttpServletRequest request, Exception e) {

        return "现在捕获的是全局异常";
    }


    // 无效允许异常
    @ExceptionHandler(BadClientCredentialsException.class)
    public VResponse<Object> illegalAccessException(HttpServletRequest request, InvalidGrantException exception) {
        return VResponse.error(1000, exception.getMessage());
    }

    // 无效允许异常
    @ExceptionHandler(InvalidGrantException.class)
    public VResponse<Object> invalidGrantException(HttpServletRequest request, InvalidGrantException exception) {
        if (exception instanceof InvalidGrantException) {
            System.out.println();
            if (exception.getMessage().contains("坏的凭证")) {
                return VResponse.success(GlobalExceptionEnum.ERROP_USER_PASSWORD);
            }
        }
        // 登录失败或者刷新token无效
        return VResponse.error(1000, exception.getMessage());
    }

    // 没有该grantType异常
    @ExceptionHandler(UnsupportedGrantTypeException.class)
    public VResponse<Object> UnsupportedGrantTypeException(HttpServletRequest request, UnsupportedGrantTypeException exception) {
        return VResponse.error(1000, exception.getMessage());
    }

}
